package com.lemon.rule.express.instruction.detail;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.lemon.rule.express.OperateData;
import com.lemon.rule.express.RunEnvironment;
import com.lemon.rule.express.instruction.op.OperatorBase;
import com.lemon.rule.express.instruction.opdata.OperateDataAttr;

public class InstructionOperator extends Instruction {
    private static final Logger logger = LoggerFactory.getLogger(InstructionCloseNewArea.class);
    OperatorBase operator;
    int opDataNumber;

    public InstructionOperator(OperatorBase aOperator, int aOpDataNumber) {
        this.operator = aOperator;
        this.opDataNumber = aOpDataNumber;
    }

    public OperatorBase getOperator() {
        return this.operator;
    }

    public void execute(RunEnvironment environment, List<String> errorList) throws Exception {
        execute(this.operator, this.opDataNumber, environment, errorList);
    }

    //
    public static void execute(OperatorBase aOperator, int aOpNum, RunEnvironment environment, List<String> errorList) throws Exception {
        OperateData[] parameters = environment.popArray(environment.getContext(), aOpNum);
        if (environment.isTrace() && logger.isDebugEnabled()) {
            String str = aOperator.toString() + "(";
            for (int i = 0; i < parameters.length; i++) {
                if (i > 0) {
                    str = str + ",";
                }
                if (parameters[i] instanceof OperateDataAttr) {
                    str = str + parameters[i] + ":" + parameters[i].getObject(environment.getContext());
                } else {
                    str = str + parameters[i];
                }
            }
            str = str + ")";
            logger.debug(str);
        }
        //
        OperateData result = aOperator.execute(environment.getContext(), parameters, errorList);
        environment.push(result);
        environment.programPointAddOne();
    }

    public String toString() {
        String result = "OP : " + this.operator.toString() + " OPNUMBER[" + this.opDataNumber + "]";
        return result;
    }
}